package com.cxx.food.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cxx.food.constant.BizType;
import com.cxx.food.entity.LikeRecord;
import com.cxx.food.mapper.LikeRecordMapper;
import com.cxx.food.service.LikeService;
import com.cxx.framework.web.CustomException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;


@Service
public class LikeServiceImpl implements LikeService {
    @Resource
    private LikeRecordMapper likeRecordMapper;


    @Override
    public Boolean addLike(BizType type, Long subjectId) {
        LambdaQueryWrapper<LikeRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LikeRecord::getSubjectId, subjectId).eq(LikeRecord::getCreateBy, StpUtil.getLoginIdAsString());
        LikeRecord like = likeRecordMapper.selectOne(queryWrapper);

        if (like != null) {
            throw new CustomException("已经点赞了");
        }

        LikeRecord newLike = new LikeRecord();
        newLike.setType(type.getCode());
        newLike.setSubjectId(subjectId);
        return likeRecordMapper.insert(newLike) == 1;
    }

    @Override
    public Boolean deleteLike(Long subjectId) {
        LambdaQueryWrapper<LikeRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LikeRecord::getSubjectId, subjectId).eq(LikeRecord::getCreateBy, StpUtil.getLoginIdAsString());
        LikeRecord like = likeRecordMapper.selectOne(queryWrapper);

        if (like == null) {
            throw new CustomException("该记录不存在");
        }

        return likeRecordMapper.deleteById(like) == 1;
    }
}
